//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at  http://www.nopCommerce.com/License.aspx. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations under the License.
// 
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
// 
// Contributor(s): _______. 
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Security;
using Tathata.Common.BLL.Entities;
using Tathata.Common.Utils;
using System.Globalization;
using Tathata.Common.BLL.Managers;
using Tathata.Common.BLL.Enums;

namespace Tathata.Common.HttpModules
{
    /// <summary>
    /// nopCommerce filter
    /// </summary>
    public class NopCommerceFilter : IHttpModule
    {
        #region Methods
        /// <summary>
        /// Handlers the AuthenticateRequest event of the application
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName];
            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = null;
                try
                {
                    authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                }
                catch (Exception)
                {
                    return;
                }
                if (!string.IsNullOrEmpty(authTicket.UserData))
                {
                    bool authenticated = false;
                    if (HttpContext.Current.User != null && HttpContext.Current.User.Identity != null)
                        authenticated = HttpContext.Current.User.Identity.IsAuthenticated;

                    if (authenticated)
                    {
                        Customer customer = CustomerManager.GetByEmail(HttpContext.Current.User.Identity.Name);
                        if (customer != null)
                        {
                            CustomerSession registeredCustomerSession = CustomerSessionManager.GetByCustomerID(customer.CustomerID);
                            if (registeredCustomerSession == null)
                            {
                                registeredCustomerSession = NopContext.Current.GetSession(true);
                                registeredCustomerSession.IsExpired = false;
                                registeredCustomerSession.LastAccessed = DateTime.Now;
                                registeredCustomerSession.CustomerID = customer.CustomerID;
                                CustomerSessionManager.SaveCustomerSession(registeredCustomerSession.CustomerSessionGUID, registeredCustomerSession.CustomerID, registeredCustomerSession.LastAccessed, registeredCustomerSession.IsExpired);
                            }

                            if (customer.Email == HttpContext.Current.User.Identity.Name && customer.Active && !customer.Deleted)
                            {
                                NopContext.Current.User = customer;
                                NopContext.Current.Session = registeredCustomerSession;
                            }
                            else
                                logout();
                        }
                        else
                            logout();
                    }
                }
            }
        }

        /// <summary>
        /// Logout customer
        /// </summary>
        protected void logout()
        {
            CustomerManager.Logout();
            HttpContext.Current.Response.Redirect("~/Login.aspx");
        }

        /// <summary>
        /// Handlers the BeginRequest event of the application
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            NopContext.Current.IsAdmin = CommonHelper.IsAdmin();
            Language currentLanguage = NopContext.Current.WorkingLanguage;
            if (currentLanguage != null)
                NopContext.Current.SetCulture(new CultureInfo(currentLanguage.LanguageCulture));

        }

        /// <summary>
        /// Handlers the EndRequest event of the application
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        protected void Application_EndRequest(object sender, EventArgs e)
        {
            try
            {
                bool sessionReseted = false;
                if (NopContext.Current["Nop.SessionReseted"] != null)
                    sessionReseted = Convert.ToBoolean(NopContext.Current["Nop.SessionReseted"]);
                if (!sessionReseted)
                {
                    NopContext.Current.SessionSaveToClient();
                    if (NopContext.Current.Session != null)
                    {
                        HttpContext context = ((HttpApplication)sender).Context;
                        if (context.User.Identity.IsAuthenticated)
                        {
                            HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                            if (cookie != null)
                            {
                                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
                                FormsAuthenticationTicket newticket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, NopContext.Current.Session.CustomerSessionGUID.ToString(), ticket.CookiePath);
                                cookie.Value = FormsAuthentication.Encrypt(newticket);
                                if (ticket.IsPersistent)
                                    cookie.Expires = ticket.Expiration;
                                context.Response.Cookies.Set(cookie);
                            }
                        }
                    }
                }
                else
                {
                }
            }
            catch (HttpException exc)
            {
                LogManager.InsertLog(LogTypeEnum.Unknown, exc.Message, exc.ToString());
            }
        }

        /// <summary>
        /// Handlers the PostAcquireRequestState event of the application
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        protected void Application_PostAcquireRequestState(object sender, EventArgs e)
        {
            if (NopContext.Current.Session != null)
            {
                //    Customer customer = NopContext.Current.Session.Customer;
                //    if (customer != null)
                //        NopContext.Current.User = customer;
            }
        }

        /// <summary>
        /// Handlers the PostRequestHandlerExecute event of the application
        /// </summary>        
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        protected void application_PostRequestHandlerExecute(object sender, EventArgs e)
        {
            
        }

        /// <summary>
        /// Handlers the PreSendRequestContent event of the application
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        protected void application_PreSendRequestContent(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Handlers the ReleaseRequestState event of the application
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        protected void Application_ReleaseRequestState(object sender, EventArgs e)
        {
        }

        /// <summary>
        ///  Initializes the NopCommerceFilter object
        /// </summary>
        /// <param name="application">The application</param>
        public void Init(HttpApplication application)
        {
            application.BeginRequest += new EventHandler(this.Application_BeginRequest);
            application.EndRequest += new EventHandler(this.Application_EndRequest);
            application.PostAcquireRequestState += new EventHandler(this.Application_PostAcquireRequestState);
            application.ReleaseRequestState += new EventHandler(this.Application_ReleaseRequestState);
            application.AuthenticateRequest += new EventHandler(this.Application_AuthenticateRequest);
            application.PreSendRequestContent += new EventHandler(this.application_PreSendRequestContent);
            application.PostRequestHandlerExecute += new EventHandler(this.application_PostRequestHandlerExecute);
        }

        /// <summary>
        /// Disposes the object
        /// </summary>
        public void Dispose()
        {
        }
        #endregion

    }
}
